<template>
    <div style="display: flex; justify-content: center; align-items: center; height: 100vh; background-color: #4e64c6; overflow: hidden">
        <div style="display: flex;background-color: white;width: 70%;height: 70%;border-radius: 10px;box-shadow: 0 0 10px rgba(0,0,0,0.3);overflow: hidden">
            <div style="flex: 1">
                <img src="@/assets/register.png" alt="" style="width: 100%; height: 100%">
            </div>


            <div style="flex: 1;display: flex;align-items: center;justify-content: center;">
                <el-form :model="account" size="medium" :rules="rules" ref="registerRef">


                    <div style="display: flex;justify-content: center;align-items: center;margin-bottom: 30px"><span
                            style="font-weight: bold;font-size: 23px;text-align: center">欢迎注册并州电子数码商城</span>
                    </div>


                    <el-form-item prop="username">
                        <el-input prefix-icon="el-icon-user" clearable v-model="account.username"
                                  placeholder="请输入用户名"></el-input>
                    </el-form-item>


                    <el-form-item prop="password">
                        <el-input prefix-icon="el-icon-lock" show-password clearable v-model="account.password"
                                  placeholder="请输入密码"></el-input>
                    </el-form-item>


                    <el-form-item prop="confirmPass">
                        <el-input prefix-icon="el-icon-lock" show-password clearable v-model="account.confirmPass"
                                  placeholder="请确认密码"></el-input>
                    </el-form-item>


                    <el-form-item prop="email">
                        <el-input prefix-icon="el-icon-s-promotion" clearable v-model="account.email"
                                  placeholder="请输入邮箱"></el-input>
                    </el-form-item>


                    <!--               请选择选择角色   -->
                    <el-form-item prop="role">
                        <el-select style="width: 350px" v-model="account.role" placeholder="请选择选择角色">
                            <el-option
                                    label="用户"
                                    value="用户">
                            </el-option>
                            <el-option
                                    label="商家"
                                    value="商家">
                            </el-option>
                        </el-select>
                    </el-form-item>


                    <!--                    <el-form-item prop="code">-->
                    <!--                        <div style="display: flex;justify-content: center;align-items: center">-->
                    <!--                            <el-input prefix-icon="el-icon-place" clearable v-model="account.code"-->
                    <!--                                      placeholder="请输入验证码"></el-input>-->
                    <!--                            <div style="flex: 1;margin-left: 30px">-->
                    <!--                                <valid-code @update:value="getCode" style="height: 36px;width: 80px"></valid-code>-->
                    <!--                            </div>-->
                    <!--                        </div>-->
                    <!--                    </el-form-item>-->

                    <div class="flex-center">
                        <input type="text" v-model="value" placeholder="请输入验证码" class="input-view">
                        <canvas id="canvas" width="150" height="43" @click="dj"
                                style="border: 1px solid #ccc"></canvas>
                    </div>


                    <el-form-item>
                        <el-button type="primary" style="width: 100%;background-color: #4e64c6;font-size: 13px"
                                   @click="register"> 注 册
                        </el-button>
                    </el-form-item>


                    <div style="display: flex;font-size: 13px">
                        <div style="flex: 1">已有账号？去<span style="color: #4e64c6;cursor: pointer"
                                                              @click="toLogin">登录</span></div>
                    </div>


                </el-form>
            </div>
        </div>
    </div>
</template>


<script>
import ValidCode from "@/conponents/ValidCode.vue";
import dateUtil from '@/utils/dateUtil';

export default ({
    name: "Register",
    components: {
        ValidCode
    },
    data() {

        // 自定义校验规则
        const validateCode = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入验证码'))
            } else if (this.code.toLowerCase() !== this.code) {
                callback(new Error('验证码错误'))
            } else {
                callback()
            }
        };

        // 确认密码校验
        const validatePassword = (rule, confirmPass, callback) => {
            if (confirmPass === '') {
                callback(new Error('请确认密码'))
            } else if (confirmPass !== this.account.password) {
                callback(new Error('两次输入的密码不一致'))
            } else {
                callback()
            }
        };

        return {
            value: '',      // 用户输入的验证码
            show_num: [],   //
            code: '',       // 验证码值
            account: {
                username: '',
                password: '',
                confirmPass: '',
                email: '',
                role: '用户',
                code: '',     // 用户输入的验证码

            },
            rules: {         // 校验规则
                username: [
                    {required: true, message: '请输入用户名', trigger: 'blur'},
                    {min: 4, message: '用户名最少为4个字符', trigger: 'blur'}
                ],
                password: [
                    {required: true, message: '请输入密码', trigger: 'blur'},
                    {min: 6, message: '密码最少为6个字符', trigger: 'blur'}
                ],
                confirmPass: [
                    {validator: validatePassword, trigger: 'blur'}
                ],
                email: [
                    {required: true, message: '请输入邮箱地址', trigger: 'blur'},
                    {type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change']}
                ],
                code: [
                    {validator: validateCode, trigger: 'blur'}
                ]
            }
        }
    },
    mounted() {
        this.show_num = [];
        this.draw();
    },
    methods: {
        // 获取验证码
        getCode(code) {
            this.code = code.toLowerCase();
        },
        register() {

            let [num1 = 0, type, num2 = 0] = this.show_num || [];
            let NUM_MAP = {
                '+': num1 + num2,
                '-': num1 - num2,
                '*': num1 * num2
            }
            if (this.value == null || this.value == '' || this.value.length == 0) {
                this.$message.error('请输入验证码！')
                return;
            }
            if (this.value == NUM_MAP[type]) {

            } else {
                this.$message.error('验证码错误！');
                this.dj()
                return;
            }

            if (this.account.role === '用户') {
                this.account.name = 'bzdzsm_' + this.account.code
                this.account.sex = '男'
                this.account.status = 1
                this.account.avatar = this.$baseUrl + '/file/download/userAvatar.png'
                // this.account.avatar = 'http://localhost:9090/file/download/userAvatar.png'
                this.account.createTime = dateUtil.formatDate(new Date())
            }

            if (this.account.role === '商家') {
                this.account.status = 4
                this.account.name = 'bzdzsm_' + this.account.code
                this.account.detail = '欢迎新商家入驻并州电子数码商城！！！'
                // this.account.avatar = 'http://localhost:9090/file/download/storeAvatar.png'
                this.account.avatar = this.$baseUrl + '/file/download/storeAvatar.png'
                this.account.createTime = dateUtil.formatDate(new Date())
            }


            // 校验验证码
            this.$refs['registerRef'].validate((valid) => {
                if (valid) {
                    // 校验通过

                    // 数据默认传值

                    // 加密密码处理
                    let pwd = this.account.password
                    pwd = this.$md5(pwd)
                    this.account.password = pwd

                    //  发送  注册  请求
                    this.$request.post('/register', this.account).then(res => {
                        if (res.code === '200') {
                            this.$message.success('注册成功！')
                            this.$router.push('/login')
                        } else {
                            this.$message.error(res.msg);
                            // location.reload();
                        }
                    })
                } else {
                    this.$message.error("注册失败，请检查输入信息!");
                    // location.reload();
                }
            });
        },
        toLogin() {
            this.$router.push('/login');
        },
        // 随机颜色
        randomColor() {
            var r = Math.floor(Math.random() * 256);
            var g = Math.floor(Math.random() * 256);
            var b = Math.floor(Math.random() * 256);
            return "rgb(" + r + "," + g + "," + b + ")";
        },
        // 绘制干扰（线条，原点）
        drawLine(context, canvas_width, canvas_height) {
            // for (var i = 0; i <= 5; i++) { //验证码上显示线条
            //     context.strokeStyle = this.randomColor();
            //     context.beginPath();
            //     context.moveTo(Math.random() * canvas_width, Math.random() * canvas_height);
            //     context.lineTo(Math.random() * canvas_width, Math.random() * canvas_height);
            //     context.stroke();
            // }
            for (var i = 0; i <= 30; i++) { //验证码上显示小点
                context.strokeStyle = this.randomColor();
                context.beginPath();
                var x = Math.random() * canvas_width;
                var y = Math.random() * canvas_height;
                context.moveTo(x, y);
                context.lineTo(x + 1, y + 1);
                context.stroke();
            }
        },
        // 绘制单个字符
        drawStr(context, txt, x) {
            var y = 20 + Math.random() * 8;//文字在canvas上的y坐标（20+0到8的随机数）
            context.font = "bold 23px 微软雅黑";

            context.fillStyle = this.randomColor(); // 随机生成一个颜色
            context.fillText(txt, x, y);
            return x + 10 + context.measureText(txt).width; //宽度
        },
        drawNum(context, randomList, currentWidth) {
            var j = Math.floor(Math.random() * randomList.length);//获取到随机的索引值 Math.floor(Math.random()*(max-min+1)+min);
            var txt = randomList[j];//得到随机的一个内容
            this.show_num.push(txt);
            return this.drawStr(context, txt, currentWidth);
        },
        draw(codeLength = 3) { // codeLength: 设置验证码长度
            let canvas = document.getElementById("canvas");//获取到canvas的对象，演员
            let context = canvas.getContext("2d");//获取到canvas画图的环境，演员表演的舞台
            let canvas_width = canvas.width;
            let canvas_height = canvas.height;
            context.clearRect(0, 0, canvas_width, canvas_height);

            this.show_num = [];
            let currentWidth = 0;
            // 数字一
            currentWidth = this.drawNum(context, new Array(100).fill(null).map((v, i) => i), currentWidth);
            // 运算类型
            currentWidth = this.drawNum(context, ['+', '-', '*'], currentWidth);
            // 数字二
            currentWidth = this.drawNum(context, new Array(10).fill(null).map((v, i) => i), currentWidth);
            // 绘制= ?
            this.drawStr(context, '= ?', currentWidth)
            // 一些干扰因素（线条，原点）
            this.drawLine(context, canvas_width, canvas_height);
        },

        dj() {
            this.value = ''
            this.draw();
        },
    }
})
</script>

<style>

.input-view {
    height: 43px;
    width: 220px;
    font-size: 20px;
    border: 1px solid #999;
    font-size: 16px;
    padding: 0 10px;
}

.flex-center {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
}

.margin-t20 {
    margin-top: 15px;
}

button {
    background: transparent;
    border: 1px solid #0440b6;
    color: #0440b6;
    margin-right: 10px;
}

</style>